import { isUndefined } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import {
  auditAfterSale,
  receiveAfterSaleReturnGoods,
  getAfterSaleBySerialNumber,
  listAfterSaleItemsForB,
} from "../../service/afterSaleService";
const router = createBrandApiMWRouter();

// 售后单商家审核
router.put(
  "/brd/:brandId/afterSale/:afterSaleSerialNumber/audit",
  async (ctx: AppCTX, next) => {
    const { brandId, afterSaleSerialNumber } = ctx.params;
    const { isRefuse, refuseReason } = ctx.request.body;
    const { userId } = ctx;
    const afterSale = await auditAfterSale({
      afterSaleSerialNumber,
      brandId,
      isRefuse,
      refuseReason,
    });

    ctx.body = afterSale;
  }
);

// 售后单退货商家同意入库
router.put(
  "/brd/:brandId/afterSale/:afterSaleSerialNumber/confirmReceive",
  async (ctx: AppCTX, next) => {
    const { brandId, afterSaleSerialNumber } = ctx.params;
    const { userId } = ctx;
    const afterSale = await receiveAfterSaleReturnGoods({
      afterSaleSerialNumber,
      brandId,
      agreeReceive: true,
    });
    ctx.body = afterSale;
  }
);

// 售后单退货商家拒绝入库
router.put(
  "/brd/:brandId/afterSale/:afterSaleSerialNumber/refuseReceive",
  async (ctx: AppCTX, next) => {
    const { brandId, afterSaleSerialNumber } = ctx.params;
    const { refuseAfterSaleReason } = ctx.request.body;
    const { userId } = ctx;
    if (isUndefined(refuseAfterSaleReason)) {
      ctx.throw(400, "拒绝理由不能为空");
    }
    console.log('refuseAfterSaleReason=>', refuseAfterSaleReason)
    const afterSale = await receiveAfterSaleReturnGoods({
      afterSaleSerialNumber,
      brandId,
      agreeReceive: false,
      refuseAfterSaleReason,
    });
    ctx.body = afterSale;
  }
);

// 获取品牌的售后列表
router.get("/brd/:brandId/afterSales", pageMW, async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { userId, limit, offset, ts } = ctx;
  const { searchTerm, searchValue } = ctx.query;
  if (!isUndefined(searchTerm) && !isSearchTerm(searchTerm)) {
    ctx.throw(400, "invalid searchTerm");
  }
  const { total, items } = await listAfterSaleItemsForB(
    {
      brandId,
      searchTerm,
      searchValue,
    },
    {
      limit,
      offset,
      ts,
    }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取售后单详情(品牌视角)
router.get(
  "/brd/:brandId/afterSale/:afterSaleSerialNumber",
  async (ctx: AppCTX, next) => {
    const { brandId, afterSaleSerialNumber } = ctx.params;
    const { userId } = ctx;

    const afterSale = await getAfterSaleBySerialNumber(afterSaleSerialNumber);
    if (isUndefined(afterSale)) {
      ctx.throw(400, "invalid afterSaleSerialNumber");
    }
    if (afterSale.brandId !== brandId) {
      ctx.throw(403, "no permit access to the aftersale");
    }

    ctx.body = afterSale;
  }
);

export default router;
